package news.dao;

import news.example.News;
import news.util.BaseDao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
public class QueryNewsDaoImpl implements IQueryNewsDao{
    BaseDao baseDao = new BaseDao();

    @Override
    public List<News> findAll() {
        List<News> list  = new ArrayList<News>();
        try {
            baseDao.openDB();
            String sql="select * from news_publish";
            baseDao.st = baseDao.conn.createStatement();
            baseDao.rs = baseDao.st.executeQuery(sql);

            while (baseDao.rs.next()){
                News news = new News();
                news.setId(baseDao.rs.getInt("id"));
                news.setTitle(baseDao.rs.getString("title"));
                news.setContent(baseDao.rs.getString("content"));
                news.setUsername(baseDao.rs.getString("username"));
                news.setDesc(baseDao.rs.getString("desc"));
                news.setUserid(baseDao.rs.getInt("userid"));
                news.setCreatetime(baseDao.rs.getDate("createtime"));
                list.add(news);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int calcTotalCount() {
        int count = 0;
        try {
            baseDao.openDB();
            String sql = "select count(*) from news_publish";
            baseDao.st = baseDao.conn.createStatement();
            baseDao.rs = baseDao.st.executeQuery(sql);
            while (baseDao.rs.next()){
                count = baseDao.rs.getInt(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public void delNews(Integer id) {
        try {
            baseDao.openDB();
            String sql = "delete from news_publish where id = ?";
            baseDao.ps = baseDao.conn.prepareStatement(sql);
            baseDao.ps.setInt(1,id);
            baseDao.ps.execute();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
